
import axios from 'axios'
import cookies from 'vue-cookies'
import { Toast } from 'vant'
import store from '../store'
import { loginUrl } from './url.js'
import utils from './utils.js'
import { refreshToken, getToken } from '../api/authorize'
var isRefreshToken = false
// 获取api域名
function getBaseUrl() {
  let _baseURL = process.env.VUE_APP_BASE_API
  if (process.env.NODE_ENV === 'production' && BASE_URL) {
    _baseURL = BASE_URL
  }
  return _baseURL
}
var timer = null
var requestNum = 0
// 创建一个axios实例
const service = axios.create({
  baseURL: getBaseUrl(),
  // baseURL: process.env.VUE_APP_BASE_API,
  timeout: 20000 // request timeout
})
// request 拦截器
service.interceptors.request.use(
  config => {
    // 这里可以自定义一些config配置
    requestNum++
    if(config.url != '/Visual/GetProductShareImage'){
      if (!timer) {
        timer = window.setTimeout(
          function () {
            Toast.loading({
              forbidClick: true,
              message: 'loading...',
              loadingType: 'spinner',
              duration: 0
            })
          }, 300)
      }
    }
    // 设置请求头
    if (cookies.get('AccessToken') && config.url !== '/Authorize/Token') {
      config.headers['Authorization'] = 'Bearer ' + cookies.get('AccessToken')
    }
    return config
  },
  error => {
    requestNum--
    if (requestNum <= 0) {
      window.clearTimeout(timer)
      Toast.clear()
      timer = null
    }
    // 这里处理一些请求出错的情况
    console.log(error)
    return Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    requestNum--
    if (requestNum <= 0) {
      window.clearTimeout(timer)
      Toast.clear()
      timer = null
    }
    // Toast.clear()
    // 这里处理一些response正常返回时的逻辑
    // 需要登录时
    if (res.State === 2) {
      console.log('未登录')
      Toast({
        message: res.Msg,
        icon: 'error'
      })
      console.log(loginUrl)
      // setTimeout(() => {
      //   window.location.href = '/m/user/Login'
      // }, 3000)
      // utils.gotoPage(loginUrl)
    } else if (res.State === 0) {
      // 请求失败
      if (res.Msg === '会员不存在' || res.Msg === '用户不存在' || res.Msg === '不存在该商户信息') {
        Toast({
          message: '账号不存在',
          icon: 'error'
        })
      } else {
        if(res.Msg != '未装修改供应商店铺'){
          Toast.fail(res.Msg)
        }
      }
      
      return res
      // return null
    } else if (res.State === 3) {
      getToken().then(res => {
        console.log(res)
        if (res) {
          store.dispatch('user/setToken', res.Data)
          localStorage.setItem('Token', res.Data.Token)
          localStorage.setItem('RefreshToken', res.Data.RefreshToken)
          window.location.reload(true)
        }
      })
      return null
    } else if (res.State === 4) {
      if (isRefreshToken === true) {
        return null
      }
      isRefreshToken = true
      refreshToken().then(res => {
        if (res) {
          if (res.State === 1) {
            store.dispatch('user/setToken', res.Data)
            localStorage.setItem('Token', res.Data.Token)
            localStorage.setItem('RefreshToken', res.Data.RefreshToken)
            window.location.reload(true)
          } else {
            getToken().then(res => {
              console.log(res)
              if (res) {
                store.dispatch('user/setToken', res.Data)
                localStorage.setItem('Token', res.Data.Token)
                localStorage.setItem('RefreshToken', res.Data.RefreshToken)
                window.location.reload(true)
              }
            })
          }
          isRefreshToken = false
        }
      })
      return null
    } else if (res.State === 5) {
      Toast({
        message: '无权操作',
        icon: 'warn-o'
      })
      return null
    } else if (res.State === 1) {
      return res
    }

  },
  error => {
    requestNum--
    if (requestNum <= 0) {
      window.clearTimeout(timer)
      Toast.clear()
      timer = null
    }
    // 这里处理一些response出错时的逻辑
    console.log(error)
    Toast({
      message: '网络异常，请检查网络后重试！',
      icon: 'replay'
    })
    return Promise.reject(error)
  }
)

export default service
